<?php
namespace app\api\controller\xilujob;


use addons\xilujob\controller\WeixinMini;
use addons\xilujob\library\Upload;
use app\common\controller\xilujob\XilujobApi;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\xilujob\resume\ModuleException;
use app\common\library\xilujob\ResumeLibrary;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Member;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\Third;
use app\common\model\xilujob\XilujobUser;
use app\common\model\xilujob\JobInterview;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\ThrowableError;
use think\Hook;
use think\Validate;
use function fast\array_get;

/**
 * 用户模块控制器
 */
class User extends XilujobApi
{
    protected $noNeedLogin = ['wxlogin','register','mobilelogin','login','wxNumberEncrypted','resetpwd'];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];

    /**
     * @ApiTitle (微信登录)
     * @ApiRoute (/api/xilujob.user/wxlogin)
     * @ApiMethod (GET)
     * @ApiParams (name="code", type="string", required=true, description="微信登录code")
     * @ApiParams (name="platform", type="string", required=true, description="登录平台")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     */
    public function wxlogin()
    {
        $param = $this->request->only(['code','platform']);
        $platform = array_get($param,'platform','wxmini');
        $wx = new WeixinMini();
        try {
            $data = $wx->wxlogin($param['code']);
            switch ($platform){
                case 'wxmini':
                    $third = Third::where('platform',$platform)->where('openid',$data['openid'])->find();
                    if(!$third){
                        $third_data = [
                            'platform'      =>  $platform,
                            'user_id'       =>  0,
                            'openname'      =>'',
                            'openid'        =>  $data['openid'],
                            'unionid'      =>  $data['unionid'] ?? '',
                            'access_token'  =>  $data['session_key'],
                            'logintime'     =>  time()
                        ];
                        $third = Third::create($third_data);
                    }else{
                        $third_data = [
                            'access_token'  =>  $data['session_key'],
                            'unionid'      =>  $data['unionid'] ?? '',
                            'logintime'     =>  time()
                        ];
                        if($third->user_id>0){
                            $user = \app\common\model\User::get(['id'=>$third->user_id]);
                            if(!$user){
                                $third_data['user_id'] = 0;
                            }
                        }
                        $third->save($third_data);
                    }
                    if($third->user_id>0){
                        #模拟登陆
                        $this->auth->direct($user->id);
                        //$user = $this->auth->getUserinfo();
                        $xiluuserData = XilujobUser::where(['user_id'=>$user->id])->find();
                        $ret = XilujobUser::switchGroup($xiluuserData, XilujobUser::GROUP_MEMBER);
                        $userinfo = \app\common\model\xilujob\XiluJobUser::formatApiRet($this->auth->getUser());
                        $data = ['userinfo' => $userinfo];
                        $data['third'] = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>1,'user_id'=>$third->user_id];
                    }else{
                        $data = ['userinfo'=>[]];
                        $data['third'] = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>0,'user_id'=>0];
                    }
                    break;
                case 'wxpublic':

                    break;
            }
        }catch (ThrowableError $e){
            $this->error($e->getMessage());
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('获取session_key成功',$data);

    }

    /**
     * @ApiTitle (微信手机号解密)
     * @ApiRoute (/api/xilujob.user/wxNumberEncrypted)
     * @ApiMethod (POST)
     * @ApiParams (name="third_id", type="int", required=true, description="第三方id")
     * @ApiParams (name="iv", type="string", required=true, description="iv")
     * @ApiParams (name="encryptedData", type="string", required=true, description="encryptedData")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
     */
    public function wxNumberEncrypted()
    {
        $param = $this->request->only(['third_id','pid','first_group_id','nickname','avatar']);
        $code = $this->request->param('code',null,null);
        $iv = $this->request->param('iv',null,null);
        $encryptedData = $this->request->param('encryptedData',null,null);

        $wx = new WeixinMini();
        $third = Third::where('id',$param['third_id'])->find();
        if(!$third) $this->error('未找到third数据',[],40001);
        if($third->user_id>0){
            $user = \app\common\model\User::get($third->user_id);
            if($user){
                $this->auth->direct($third->user_id);

                $xiluuserData = XilujobUser::get(['user_id'=>$user->id]);
                try {
                    $ret = XilujobUser::switchGroup($xiluuserData, XilujobUser::GROUP_MEMBER);
                }catch (Exception $e){
                    $this->error($e->getMessage());
                }
                $user = $this->auth->getUser();
                $userinfo = \app\common\model\xilujob\XiluJobUser::formatApiRet($user);
                $third = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>1,'user_id'=>$third->user_id];
                $this->success('手机号已经注册成功',['userinfo'=>$userinfo,'third'=>$third]);
            }
        }

        Db::startTrans();
        try {
            //$data = $wx->wxNumberEncrypted($third['access_token'],$param['iv'],$param['encryptedData']);
            //新版本授权
            if($code){
                $data = $wx->getPhoneNumber($code);
            }else if($iv && $encryptedData){
                $data = $wx->wxNumberEncrypted($third['access_token'],$iv,$encryptedData);
            }else{
                throw new Exception("获取手机号参数错误");
            }
            $user = \app\common\model\User::where('mobile',$data['phoneNumber'])->find();
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $extend = [
                    'nickname'=>$param['nickname'],
                    'avatar'=>$param['avatar']
                ];
                $ret = $this->auth->register($data['phoneNumber'], Random::alnum(), '', $data['phoneNumber'], $extend);
            }

            if ($ret) {
                $userinfo = $this->auth->getUserinfo();
                //判断是否已经有身份了
                $xilujobuser = XilujobUser::getByUserId($userinfo['id']);

                if(!$xilujobuser){
                    #创建用户身份账号
                    $xiluuserData['user_id'] = $userinfo['id'];
                    $xiluuserData['group_id'] = 1;
                    $xiluuserData['source'] = XilujobUser::SOURCE_REGISTER;
                    //添加邀请人信息
                    $pid = array_get($param,'pid');
                    $first_group_id = array_get($param,'first_group_id');
                    if($pid && $first_group_id){
                        $puser = XilujobUser::where('user_id',$pid)->find();
                        if($puser && !in_array($pid,[$userinfo['id'],$puser['first_pid'],$puser['second_pid']])){
                            $xiluuserData['my_group_id'] = 1;
                            $xiluuserData['first_group_id'] = $first_group_id;
                            $xiluuserData['first_pid'] = $pid;
                            $xiluuserData['second_group_id'] = $puser['first_group_id'];
                            $xiluuserData['second_pid'] = $puser['first_pid'];
                            $xiluuserData['bindtime'] = time();
                        }
                    }
                    XilujobUser::create($xiluuserData);
                }else{
                    $xiluuserData['user_id'] = $xilujobuser['user_id'];
                    $xiluuserData['group_id'] = $xilujobuser['group_id'];
                    $xiluuserData['source'] = $xilujobuser['source'];
                }

                #创建求职者member账号
                $member = Member::getByUserId($userinfo['id']);
                if(!$member){
                    $modelData['user_id'] = $userinfo['id'];
                    Member::create(['user_id'=>$userinfo['id']]);
                }
                #更新third表字段
                $third->user_id = $userinfo['id'];
                $third->save();
                $userinfo = array_merge($userinfo,$xiluuserData);
                $third = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>1,'user_id'=>$third->user_id];
                $data = ['userinfo' => $userinfo,'third'=>$third];
            } else {
                $this->error($this->auth->getError());
            }
        }catch (DecryptException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (ThrowableError $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success(__('登录成功'), $data);
    }

    /**
     * @ApiTitle (修改会员个人信息)
     * @ApiRoute (/api/xilujob.user/profile)
     * @ApiMethod (POST)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name="avatar", type="string", required=true, description="头像")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $user->visible(['avatar','nickname']);
        if($this->request->isPost()) {
            $nickname = $this->request->post('nickname');
//        $bio = $this->request->request('bio');
            $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
            $user->nickname = $nickname;
//        $user->bio = $bio;
            $user->avatar = $avatar;
            $user->save();
            $this->success('', ['profile'=>$user]);
        }
        $this->success('',['profile'=>$user]);
    }

    /**
     * 企业注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $captcha = $this->request->post('captcha');
        $code = $code ? $code : $captcha ;
        $group_id = $this->request->post('group_id');
        if (!$mobile || !$password) {
            $this->error(__('未知参数'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }
        if($mobile && $user = \app\common\model\User::getByMobile($mobile)){
            #判断是不是企业身份，并且是否已经有企业身份
            if($group_id == 2){
                $count = CompanyProfile::where('user_id',$user['id'])->count();
                if($count>0){
                    $this->error('当前手机号或邮箱已注册过企业账号');
                }
            }else{
                $this->error(__('手机号已注册过'));
            }
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('验证码不正确'));
        }

        try {
            $userData = ['mobile'=>$mobile,'email'=>$email??'','username'=>$mobile,'password'=>$password];
            $group_model = XilujobUser::add_user($group_id,$userData,[],[],$user ?? []);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $ret = $this->auth->direct($group_model->user_id);
        if ($ret) {
            $user = $this->auth->getUser();

            //身份切换为企业
            $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
            $user->token = $this->auth->getToken();
            try {
                $ret = XilujobUser::switchGroup($xilujobuser, XilujobUser::GROUP_COMPANY);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }

            $data = ['userinfo' => \app\common\model\xilujob\XiluJobUser::formatApiRet($user)];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 企业登录手机验证码登录
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('验证码错误'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('账号已被锁定'));
            }
            $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
            if(!$xilujobuser || !$xilujobuser->enterprise_model){
                $this->error('当前账号未申请企业账号');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error('账号不存在');
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $userinfo = $this->auth->getUser();
            $userinfo->token = $this->auth->getToken();
            try {
                $ret = XilujobUser::switchGroup($xilujobuser, XilujobUser::GROUP_COMPANY);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $data = ['userinfo' => \app\common\model\xilujob\XiluJobUser::formatApiRet($userinfo)];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 企业登录手机密码登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        #去判断用户是什么身份
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user = \app\common\model\User::get([$field => $account]);
        if (!$user) {
            $this->error('账号错误');
        }
        if ($user->status != 'normal') {
            $this->error('企业账号已被锁定');
        }
        if ($user->password != $this->auth->getEncryptPassword($password, $user->salt)) {
            $this->error('密码错误');
        }
        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
        if(!$xilujobuser || !$xilujobuser->enterprise_model){
            $this->error('当前账号未申请企业账号');
        }
        $ret = $this->auth->direct($user->id);
        if ($ret) {
            $user = $this->auth->getUser();
            $user->token = $this->auth->getToken();
            try {
                $ret = XilujobUser::switchGroup($xilujobuser, XilujobUser::GROUP_COMPANY);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $data = ['userinfo' => \app\common\model\xilujob\XiluJobUser::formatApiRet($user)];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("password");
        $repeat_password = $this->request->post("repeat_password");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha || !$repeat_password) {
            $this->error(__('Invalid parameters'));
        }
        if($repeat_password !== $repeat_password){
            $this->error(__('两次密码不一致'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }
            Sms::flush($mobile, 'resetpwd');
        }
        else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiTitle (个人用户 - 个人中心数据)
     * @ApiSummary (用户中心数据，包含用户基本信息、简历基本信息)
     * @ApiRoute (/api/xilujob.user/info)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     */
    public function info() {
        $user = $this->auth->getUser();

        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);

        $resume = Resume::getUserResume($this->auth->id);
        if(!$resume) {
            // 进入个人中心即创建一份简历
            $resume = ResumeLibrary::createResume($this->auth->getUser());
            $resume = Resume::getResume($resume->id);
        }
        $resume->personal;
        try {
            $recommendJobTotal = \app\common\model\xilujob\Job::recommendJobs($user, ['city_id'=>$this->cityId,'pagesize'=>1])['total'];
        }catch (\Exception $e) {
            $recommendJobTotal = 0;
        }
        $data = [
            'userinfo' => XilujobUser::formatApiRet($user),
            'summary' => [
                'resume' => $resume,
                'avatar' => $user->avatar,
                'nickname' => $user->nickname,
                'message_count' => $xilujobuser->system_message + $xilujobuser->personal_message + $xilujobuser->activity_message,
                'discover_post_life_count' => $xilujobuser->discover_message,
                'recommend_jobs_count' => $recommendJobTotal,
                'job_intention_count'   =>  count($resume->job_intention),
                'interview_count' => JobInterview::where('user_id',$this->auth->id)->where('status',JobInterview::STATUS_INTERVIEW_SENT)->count(),
                'info_complete' => $resume?$resume->complete_percent:0,
                'not_comment_count' => JobInterview::where('user_id',$this->auth->id)->where('status','in',[JobInterview::STATUS_INTERVIEW_FAILED, JobInterview::STATUS_INTERVIEW_PASSED
                ])->where('has_comment',0)->count(),
            ],
        ];
        $this->success('查询成功', $data);
    }

    /**
     * @ApiTitle (我的在线简历)
     * @ApiSummary (查询用户在线简历)
     * @ApiRoute (/api/xilujob.user/my_resume)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     */
    public function my_resume() {
        $resume = Resume::getUserResume($this->auth->id, true);
        if(!$resume) {
            $resume = \app\common\library\xilujob\ResumeLibrary::createResume($this->auth->getUser());
            $resume = Resume::getResume($resume->id, true);
        }
        $resume->relationQuery(['resume_files']);
        $resume->personal->hide_mobile = 0;//不隐藏手机信息
        $resume->hide_education = 0;//不隐藏教育经历
        $this->success('查询成功', ['resume'=>$resume]);
    }

    /**
     * 编辑或添加模块内容
     */
    public function save_module() {
        $id = $this->request->post('id',null);
        if($id) {
            return $this->edit_module();
        }else {
            return $this->add_module();
        }
    }

    protected function add_module() {
        $module = $this->request->post('module','');
        $data = $this->request->post();
        $resume = Resume::getUserResume($this->auth->id);
        $resumeLibrary = ResumeLibrary::getResumeLibrary($resume, $this->auth->getUser());
        try {
            $ret = $resumeLibrary->add($module, $data);
            Hook::listen("xilujob_resume_complete",$resume);
        }catch (ModuleException $e){
            $this->error($e->getMessage());
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('保存成功',['model'=>$ret, 'complete_percent'=>$resume->complete_percent]);
    }

    protected function edit_module() {
        $module = $this->request->post('module','');
        $data = $this->request->post();
        $resume = Resume::getUserResume($this->auth->id);
        $resumeLibrary = ResumeLibrary::getResumeLibrary($resume,$this->auth->getUser());
        Db::startTrans();
        try {
            $ret = $resumeLibrary->edit($module, $data);
            Hook::listen("xilujob_resume_complete",$resume);
        }catch (ModuleException $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        Db::commit();
        $this->success('保存成功', ['model'=>$ret, 'complete_percent'=>$resume->complete_percent]);
    }


    /**
     * @ApiTitle (删除简历模块数据)
     * @ApiSummary (删除简历模块数据)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.user/del_module)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=module, type=string, require=true, description="模块类型：education、work/skill")
     * @ApiParams (name=id, type=int, require=true, description="模块数据主键")
     */
    public function del_module() {
        $module = $this->request->post('module','');
        $resume = Resume::getUserResume($this->auth->id);
        $resumeLibrary = ResumeLibrary::getResumeLibrary($resume, $this->auth->getUser());
        $ret = $resumeLibrary->del($module, $this->request->post('id'));
        if(is_string($ret)) {
            $this->error($ret);
        }
        $this->success('删除成功', ['model'=>$ret, 'complete_percent'=>$resume->complete_percent]);
    }


    /**
     * 获取可更换的身份 & 提交更换身份
     */
    public function switch_group() {
        $user = $this->auth->getUser();
        $xilujobuser = XilujobUser::where('user_id',$user->id)->find();
        if($this->request->isPost()) {
            $groupId = $this->request->post('group_id');
            try {
                $ret = XilujobUser::switchGroup($xilujobuser, $groupId);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }

            $this->success('', ['userinfo' => XilujobUser::formatApiRet($user)]);

        }
        $groups[] = ['id'=>XilujobUser::GROUP_MEMBER,'name'=>'普通用户'];
//        $enterpriseGroups = [
//            ['id'=>XilujobUser::GROUP_COMPANY, 'name'=>'企业用户'],
//            ['id'=>\app\common\model\User::GROUP_LABOUR, 'name'=>'企业用户 - 劳务店铺'],
//        ];
//        if(!$user->group_model instanceOf Member && $user->group_model->audit_status==0) {
//            //未提交企业信息
//            $groups = array_merge($groups, $enterpriseGroups, [
//                ['id'=>\app\common\model\User::GROUP_TRAINER, 'name'=>'企业用户 - 培训机构']
//            ]);
//        }
//        else if($user->enterprise_group_id) {
//            $groups[] = $enterpriseGroups[$user->enterprise_group_id-2];
//            $groups[] = ['id'=>\app\common\model\User::GROUP_TRAINER, 'name'=>'企业用户 - 培训机构'];
//        }
//        else if($user->trainer_group_id) {
//            $groups = array_merge($groups, [
//                ['id'=>\app\common\model\User::GROUP_COMPANY, 'name'=>'企业用户'],
//                ['id'=>\app\common\model\User::GROUP_TRAINER, 'name'=>'企业用户 - 培训机构']
//            ]);
//        }
//        else {
//            $groups = array_merge($groups, $enterpriseGroups, [
//                ['id'=>\app\common\model\User::GROUP_TRAINER, 'name'=>'企业用户 - 培训机构']
//            ]);
//        }
        $groups = array_merge($groups, [
                ['id'=>XilujobUser::GROUP_COMPANY, 'name'=>'企业用户'],

            ]);
        $this->success('', ['groups'=>$groups,'group_id'=>$xilujobuser->group_id]);
    }


    /**
     * @AipTitle (查询用户设置)
     * @ApiSummary (查询用户设置)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.user/privacy_setting)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     */
    public function privacy_setting() {
        $resume = Resume::getUserResume($this->auth->id, true);
        if(!$resume) {
            $resume = \app\common\library\xilujob\ResumeLibrary::createResume($this->auth->getUser());
        }
        if($this->request->isPost()) {
            $hideMobile = $this->request->post('hide_mobile');
            $hideEducation = $this->request->post('hide_education');
            $resumeStatus = $this->request->post('resume_status');
            if($hideMobile!==null) {
                $resume->personal->save(['hide_mobile'=> $hideMobile ? 1:0]);
            }
            if($hideEducation!=null) {
                $resume->save(['hide_education'=>$hideEducation ? 1:0]);
            }
            if($resumeStatus!==null) {
                $resume->save(['status'=>$resumeStatus]);
            }
        }
        $this->success('',[
            'hide_mobile' => $resume->personal->hide_mobile,
            'hide_education' => $resume->hide_education,
            'resume_status' => $resume->status
        ]);
    }

    /**
     * @AipTitle (新手帮助)
     * @ApiSummary (新手帮助)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xilujob.user/help_list)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     */
    public function help_list(){
        $helps = Db::name('xilujob_newbie_help')->where('status','1')->order('weigh')->select();
        $this->success('查询成功',$helps);
    }

    /**
     * @AipTitle (新手帮助)
     * @ApiSummary (新手帮助)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xilujob.user/help_detail)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     */
    public function help_detail(){
        $id = $this->request->param('id');
        $row = Db::name('xilujob_newbie_help')->where('id',$id)->where('status','1')->order('weigh')->find();
        $this->success('查询成功',$row);
    }

    /**
     * 通过third获取wx账号信息
     */
    public function wx_account() {
        $third_id = $this->request->param('third_id');
        $account = Third::where('id', $third_id)->find();
        if($account) {
            $this->success('', ['wx_account'=>['third_id'=>$account->id,'openname'=>$account->openname,'binding'=>$account->user_id?1:0,'user_id'=>$account->user_id]]);
        }
        $this->error('');
    }

    /**
     * 更新账号信息
     */
    public function wxauth(){
        $third_id = $this->request->post('third_id',0);
        $avatar = $this->request->post('avatar');
        $nickname = $this->request->post('nickname');
        if(!$third_id || !$nickname) $this->error('参数错误');
        $third = Third::get($third_id);
        if(!$third) $this->error('账号信息不存在');
        $third->save(['openname'=>$nickname,'avatar'=>$avatar]);
        $user = $this->auth->getUser();
        if(!$user->avatar || strpos($user->avatar,'data:image') !== false){
            $user->avatar = $avatar;
            $user->nickname = $nickname;
            $user->save();
        }
        #更新简历里的头像
        $resume = Resume::where('user_id',$user->id)->find();
        if($resume && !$resume->personal->avatar){
            $resume->personal->avatar = $avatar;
            $resume->save();
        }
        $this->success('更新成功',['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>$third->user_id?1:0,'user_id'=>$third->user_id]);
    }


    /**
     * 个人-企业分享海报
     */
    public function poster_info() {
        $uid = $this->auth->id;
        $xiluuser = XilujobUser::get(['user_id'=>$uid]);
        $wx = new WeixinMini();
        $page = "pages/public/index";
        $res = $wx->getUnlimited("uid=".$uid."&group=".$xiluuser->group_id,$page);
        if(!$res) $this->error('获取小程序二维码失败');
        $path = "/runtime/xilujob/user/";
        if (!file_exists(ROOT_PATH . $path)) {
            @mkdir(ROOT_PATH . $path, 0777, true);
        }
        $filename = $uid.'.png';
        $qrcode = $path.$filename;
        file_put_contents(ROOT_PATH.$qrcode,$res);

        // 上传成功后该文件将被删除，请务必使用临时文件，这里$tempFile为你服务器准备上传的文件
        $tempFile = ROOT_PATH . $qrcode;
        $qrcode = (new Upload())->uploadApi($tempFile);
        if($xiluuser->group_id == XilujobUser::GROUP_COMPANY){
            $enterprise = EnterpriseInfo::where('user_id',$uid)->field('company_name,logo')->find();
            $img = $enterprise['logo'];
            $nickname = $enterprise['company_name'];
        }else{
            $img = $this->auth->avatar;
            $nickname = $this->auth->nickname;
        }

        $this->success('',[
            'text1' => $nickname,
            'img2'=> cdnurl($qrcode,true),
            'img1'=> $img?cdnurl($img,true):request()->domain().'/assets/img/avatar.png',
        ]);
    }

}